#ifndef UTILS_H
#define UTILS_H

#include <QString>
#include <QFile>
#include <QTextStream>
#include <QCoreApplication>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>

namespace PathUtils
{
static QString resource(const QString &res)
{
    auto s = QCoreApplication::applicationDirPath();
    if(!s.endsWith("/") && !res.startsWith("/"))
    {
        s += "/";
    }
    s += res;
    return s;
}
}

namespace StringUtils
{
static QString formatQString(QString format, const QString arg)
{
    std::string fstr = format.toStdString();
    std::string argStr = arg.toStdString();
    return QString::asprintf(fstr.c_str(), argStr.c_str());
}
template<typename T>
static QString formatQString(QString format, const T arg)
{
    std::string fstr = format.toStdString();
    return QString::asprintf(fstr.c_str(), arg);
}

}

namespace FileUtils {
static QString readTxt(const QString &filePath, const QString &byDefault)
{
    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return byDefault;
    QTextStream in(&file);
    QString all = in.readAll();
    file.close();
    return all;
}

static bool writeTxt(const QString &filePath, const QString &content)
{
    QFile file(filePath);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(&file);
    out << content << Qt::endl;
    file.close();
    return true;
}
}

namespace UIUtils
{
static QString winTitle(const QString &title)
{
    return QCoreApplication::applicationName() + " - " + title;
}
}

namespace JsonUtils
{
static QJsonObject toJson(const QByteArray &bytearray)
{
    QJsonDocument doc = QJsonDocument::fromJson(bytearray);
    return doc.object();
}
}

#endif // UTILS_H
